import os
import ssl

import paho.mqtt.client as mqtt

from app.conf import settings
from app.api.generate.utils.generate_queue.process_message import msg_process

mqtthost = settings.MQTT_HOST
mqttport = settings.MQTT_PORT
mqttuser = settings.MQTT_USER
mqttpwd = settings.MQTT_PASSWORD
mqttTLS = settings.MQTT_TLS
sub_topic_list = settings.MQTT_TOPIC_LIST


def on_connect(client, userdata, flags, rc):
    print('mqtt链接')
    for sub_topic in sub_topic_list:
        client.subscribe(sub_topic)


def on_message(client, userdata, msg):
    # print(msg.topic,msg.payload.decode('utf-8'))
    # 处理消息
    msg_process(msg.topic, msg.payload.decode('utf-8'))


def on_subscribe(client, userdata, mid, granted_qos):
    print('订阅：', sub_topic_list)
    # print("On Subscribed: qos = %d" % granted_qos)


def on_disconnect(client, userdata, rc):
    print('断开链接')
    # if rc != 0:
    #     print("Unexpected disconnection %s" % rc)


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1)
client.username_pw_set(mqttuser, mqttpwd)
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect
# if mqttTLS:
#
#     path = os.getcwd() + '/wchime.xyz_bundle.crt'
#     client.tls_set(path, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2)
#     client.tls_insecure_set(True)
client.connect(host=mqtthost, port=mqttport, keepalive=90, bind_address="")
# client.loop_forever()
# client.loop_start()









